package com.sky.web.app;

import com.sky.dto.DishPageDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/dish")
public class AppDishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 查询菜品列表
    @GetMapping("/list")
    public Result list(Long categoryId) {//1. 接收参数
        //一、先查询redis缓存,有就直接返回
        String key = "DISH:" + categoryId;
        if (redisTemplate.hasKey(key)) {
            log.info("查询redis");
            return Result.success(redisTemplate.opsForValue().get(key));
        } else {
            log.info("查询数据库");
            //二、如果缓存没有，再查询数据库，同步缓存
            DishPageDTO dto = new DishPageDTO();
            dto.setCategoryId(categoryId);
            dto.setStatus(1);// 启售
            List<DishVO> list = dishService.findList(dto);
            // 同步缓存
            redisTemplate.opsForValue().set(key, list);
            return Result.success(list);
        }
    }
}
